import { Component, OnInit, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { CommonService } from '../../../../services-common/common.service';
import { PermissionService } from '../../../../service/permission.service';
import { StorageCommonService } from '../../xstorage-manage-services/storage-common.service';
import { StorageWarehousOrderService } from '../../xstorage-manage-services/storage-warehous-order.service';

@Component({
  selector: 'app-storage-warehous-operation',
  templateUrl: './storage-warehous-operation.component.html',
  styleUrls: ['./storage-warehous-operation.component.scss']
})
export class StorageWarehousOperationComponent implements OnInit {
  @ViewChild('followUpRef') followUpRef: any;

  // 路由缓存恢复时
  static updateCache: any = null;
  searchOptions: any = [
    { type: 1, labelText: '入库单号', valueKey: 'warehousingNumber', value: '' },
    {
      type: 2,
      labelText: '入库仓库',
      valueKey: 'whIds',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'id', label: 'name' },
      selectOptions: [],
    }
  ];
  searchParams: any = {};

  putTypeOptions: any[] = []; // 入库类型options
  warehouseOptions: any[] = []; // 入库仓库options

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  // 跟进 Modal
  initParams: any = {
    type: 3, // type 1、采购 2、SN 3、入库单 4、出库单
    relationInformation: ''
  };

  constructor(
    private msg: NzMessageService,
    private commonService: CommonService,
    private modal: NzModalService,
    public permission: PermissionService,
    private storageCommonService: StorageCommonService,
    private services: StorageWarehousOrderService
  ) { }

  ngOnInit(): void {
    this.loadPutTypeOptions();
    this.loadWarehouseOptions();

    StorageWarehousOperationComponent.updateCache = () => {
      this.loadPutTypeOptions();
      this.loadWarehouseOptions();
      this.loadTable();
    }
  }

  // 入库类型options
  async loadPutTypeOptions() {
    const res: any = await this.commonService.getDictList('inbound_type');
    this.putTypeOptions = res || [];
  }

  // 查询仓库Options
  async loadWarehouseOptions() {
    let params = {
      page: 1,
      pageSize: 1000
    }
    const {code, data, message}: any = await this.storageCommonService.getWarehouseList(params);
    if (code === 0) {
      this.warehouseOptions = data.records || [];
      setTimeout(() => {
        this.setSearchOption(data.records, 'whIds');
      })
    } else {
      this.msg.error(message);
    }
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      state: "3, 4", // 入库中、入库完毕
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const {code, data, message}: any = await this.services.getWarehousingList(params);
    this.tableParams.loading = false;

    if (code === 0) {
      this.tableParams.tableData = data.records || [];
      this.tableParams.total = data.total || 0;
    } else {
      this.msg.error(message);
    }
  }

  queryResetData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  confirmWarehous(item: any) {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '该操作不可逆，入库后该单将彻底不可操作，是否继续?',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          ids: [item.id],
          state: 4 // 入库完毕
        }
        const res: any = await this.storageCommonService.updateExamineData(params);

        if (res.code === 0) {
          this.msg.success('操作成功');
          this.loadTable();
        } else {
          this.msg.error(res.message);
        }
      },
      nzCancelText: '取消'
    });
  }

  // 跟进
  showFollowModal(item: any) {
    this.initParams.relationInformation = item.id;
    this.followUpRef.isModelVisible = true;
  }

  /**
   * other
   * ----------------------------------------------------------------
   */
  setSearchOption(array: Array<any>, val: string) {
    let temIndex = this.searchOptions.findIndex((item: any) => item.valueKey === val);
    this.searchOptions[temIndex].selectOptions = array || [];
  }

  // Filter Text
  filterText(arrs: Array<any>, keyVal: any, idKey: string) {
    let tempObjs: any = {};
    if (arrs.length) {
      tempObjs = arrs.find(item => item[idKey] == keyVal);
    }

    return tempObjs?.name || '-';
  }
}
